package org.upt.dcda;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.upt.dcda.db.BookEntity;
import org.upt.dcda.db.OrderEntity;
import org.upt.dcda.db.OrderItemEntity;
import org.upt.dcda.db.UserEntity;
import org.upt.dcda.exceptions.BookstoreException;
import org.upt.dcda.exceptions.EmptyOrderListException;
import org.upt.dcda.exceptions.UserNotFoundException;

/**
 * Session Bean implementation class OrderManagerBean
 */
@Stateless
@LocalBean
public class OrderManagerBean implements OrderManagerBeanRemote,
		OrderManagerBeanLocal
{

	@PersistenceContext
	private EntityManager	entityManager;

	/**
	 * Default constructor.
	 */
	public OrderManagerBean()
	{
		// TODO Auto-generated constructor stub
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public void placeOrder(UserEntity user, OrderItem[] orderItems)
			throws BookstoreException
	{
		try
		{
			if (orderItems.length != 0)
			{
				if (user == null)
					throw new UserNotFoundException();

				OrderEntity order = new OrderEntity();
				order.setUser(user);
				entityManager.persist(order);

				for (OrderItem oi : orderItems)
				{
					OrderItemEntity oie = new OrderItemEntity();
					BookEntity book = entityManager.find(BookEntity.class,
							oi.id);
					oie.setBook(book);
					oie.setOrderitemsQuantity(oi.quantity);
					oie.setOrder(order);
					entityManager.persist(oie);
				}
			}
			else
			{
				throw new EmptyOrderListException();
			}
		}
		catch (BookstoreException be)
		{
			throw be;
		}
		catch (Throwable t)
		{
			throw new BookstoreException("Caught exception: " + t.toString(), t);
		}

	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public List<OrderEntity> viewAllOrders() throws BookstoreException
	{

		try
		{

			Query query = entityManager
					.createNamedQuery(OrderEntity.VIEW_ALL_ORDERS);

			List<OrderEntity> resultList = (List<OrderEntity>) query
					.getResultList();
			return resultList;

		}
		catch (Throwable t)
		{
			throw new BookstoreException("Caught exception: " + t.toString(), t);
		}
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public List<OrderEntity> viewUserOrders(int userId)
			throws BookstoreException
	{
		try
		{

			Query query = entityManager
					.createNamedQuery(OrderEntity.VIEW_USER_ORDERS);

			List<OrderEntity> resultList = (List<OrderEntity>) query
					.getResultList();
			return resultList;

		}
		catch (Throwable t)
		{
			throw new BookstoreException("Caught exception: " + t.toString(), t);
		}
	}

}
